package com.itheima.reggie.result;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.sql.SQLIntegrityConstraintViolationException;

/*
* 全局异常处理
* */
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    private R<String> exceptionHandler(SQLIntegrityConstraintViolationException e) {
        log.info(e.getMessage());
        if (e.getMessage().contains("Duplicate entry")) {
            String[] s = e.getMessage().split(" ");
            return R.error(s[2] + "已存在");
        }
        return R.error("未知错误");
    }

/*
* 自定义业务异常
* */
    @ExceptionHandler(CustomizeException.class)
    private R<String> exceptionHandler(CustomizeException e) {
        log.info(e.getMessage());

        return R.error(e.getMessage());
    }
}
